<?php
if( !defined( 'MEDIAWIKI' ) ){
	die(-1);
}

global $IP;	
	
require_once( 'SpecialPage.php' );
require_once($IP.'/includes/SoundShareUtils.php');
require_once($IP.'/includes/ss_classes/ss_SimilarFiles.php');



$wgHooks['ArticleViewHeader'][] = "wfMP3Info";
$wgHooks['InitializeArticleMaybeRedirect'][] = "wfMP3Redirect";

function wfMP3Info()
{
	global $wgTitle, $wgOut, $wgRequest;
	if ($wgTitle->mNamespace==NS_SONG) {
		$sss = new MP3();
		$sss->id = $wgRequest->getInt('file', null);
		wfProfileIn($sss->render_file());
	}
	return true;
}

function wfMP3Redirect($title, $request, &$ignoreRedirect, &$target, &$article)
{
	$idfile = $request->getInt('file', null);
       	if ($title->mNamespace!=NS_SONG || $idfile!=null) return true;

	$dbr = wfGetDB( DB_SLAVE );
       	$idres = $dbr->query("SELECT IdFile FROM ss_tags WHERE artistkey='{$title->mArtistKey}' and titlekey='{$title->mNoArtistKey}' and idfile is not null");
	if ($idrow = $dbr->fetchrow($idres))
	{
		$target = $title->getLocalURL("file=".$idrow[0]);
		$article->mIsRedirect = true;
	}
	$dbr->freeResult($idres);
	return true;
}

class MP3 extends IncludableSpecialPage {
	

	function MP3()
	{
	  SpecialPage::SpecialPage( 'MP3','',true, false,
	                             'default',true);
	}
	
	function getCommentsFile($FileId, $artist, $filename){
	    global $wgOut, $wgUser, $wgScript,$wgLang;
	  
                $lang = $wgLang->getCode();
                $FileId = mysql_real_escape_string( $FileId );

		$dbr = wfGetDB( DB_SLAVE );
		$sql = "SELECT * FROM ss_file_comments  WHERE id_file ={$FileId}  AND lang ='{$lang}' ";
    		$res = $dbr->query( $sql );
		
		$out .= '<div id="usercomments" class="sscomment"><h2>'.wfMsg( 'user_comments' ).'</h2>';

		if( !$wgUser->isLoggedIn() ) {
			$out .= '<div class="comment-link">';
                       
                        $out .= '<a rel="nofollow" href="'.$wgScript.'?title=Special:UserLogin&type=signup&returnto='
                                .htmlspecialchars($_SERVER['SCRIPT_URL']).'">'.wfMsg( 'login' ).'</a> '.wfMsg( 'to_post_a_comment' ).' <img alt="login to add a comment about this mp3" src="/skins/soundshare/discussionitem_icon.gif" />';
			$out .= '</div>';
		}
		
		
		
		$count = 0;
		while ($row = $dbr->fetchObject( $res )) {
		  ++$count;
		  
		  $avatar = new wAvatar( $row->id_user, 'm' );
		  
		  //fetch comment votes
		  $dbs = wfGetDB( DB_SLAVE );
		  $sql_votos_comment = "SELECT SUM(value) AS 'votosuma' FROM ss_file_comments_votes WHERE id_comment = " .$row->id_comment;
		  $resvote = $dbs->query( $sql_votos_comment );
		  $rowvote = $dbs->fetchObject( $resvote );

			  
		  
		  $out .= '<div class="comment">
				
				<h4><a href="'.$wgScript.'/User:'.$wgUser->whoIs($row->id_user).'">'.$avatar->getAvatarURL().'</a>
				<span class="count"><a href="/download/'.$artist.'/'.$filename.'#'.$row->id_comment.'">#'.$count.'</a>
				.<strong><a href="'.$wgScript.'/User:'.$wgUser->whoIs($row->id_user).'">'.$wgUser->whoIs($row->id_user).'</a></strong> on '.date("g:i a F j, Y ", strtotime($row->date)).
				'</span></h4>'.htmlspecialchars($row->comment);
				
				
		 
			$out .= '<div class="dedos">';
				
			if( $wgUser->isLoggedIn() ) {  	
				$out .=	'
				
				
				<a title="vote -1" id="linkdedodown'.$row->id_comment.'"
				href="javascript:voteComment(-1,'.$row->id_comment.')">
				<img id="dedodown'.$row->id_comment.'" border="0" alt="" src="/skins/soundshare/dedo_down.png" /></a>
				
				<a title="vote +1" id="linkdedoup'.$row->id_comment.'"
				href="javascript:voteComment(1,'.$row->id_comment.')">
				<img id="dedoup'.$row->id_comment.'" border="0" alt="" src="/skins/soundshare/dedo_up.png" /></a>
				';
			}  
				  
				   $out .= '<br>
				   <small>karma: <cite id="countervote'.$row->id_comment.'">'.$rowvote->votosuma = ( !is_null($rowvote->votosuma) ? $rowvote->votosuma : 0).'</cite></small>
				   </div></div>';
				   
		  $dbs->freeResult( $resvote );//free vote 
		}
		
		$out .= '</div>'; //close comment container
		
		return $out;
		
		$dbr->freeResult( $res );
		
	}
	
	// getRatingFile function	
	function getRatingFile($idfile){
		  
		  global $wgUser;
		  
		  $userid = $wgUser->getId();
		  
		  if( $wgUser->isLoggedIn()){ //if user is logged in fetch the users rating
		    
		    $dbr = wfGetDB( DB_SLAVE );
		    $sql = "SELECT rating
			FROM ss_file_rating WHERE id_rating_file = '$idfile' AND id_user = '$userid'";
  
			$res = $dbr->query( $sql );
			$row = $dbr->fetchObject( $res );
			$ratingpix = $row->rating*25;
			$out = '<div class="file-rating">You rate this file:
				<ul class="star-rating">';
		   $out .= '<li class="current-rating" id="current-rating" style="width:'.$ratingpix.'px"></li>';
		   $out .= ' <li><a href="javascript:rateFile(1,'.$idfile.')" title="1 star of 5" class="one-star">1</a></li>
                                <li><a href="javascript:rateFile(2,'.$idfile.')" title="2 stars of 5" class="two-stars">2</a></li>
                                <li><a href="javascript:rateFile(3,'.$idfile.')" title="3 stars of 5" class="three-stars">3</a></li>
                                <li><a href="javascript:rateFile(4,'.$idfile.')" title="4 stars of 5" class="four-stars">4</a></li>
                                <li><a href="javascript:rateFile(5,'.$idfile.')" title="5 stars of 5" class="five-stars">5</a></li>
                            </ul>
                        </div>';
		   
		  } else { //if user NOT logged in, show the rating global average for this file
		    
			$dbr = wfGetDB( DB_SLAVE );
       			$sql = "SELECT AVG(rating) as ratzinger FROM ss_file_rating WHERE id_rating_file = '$idfile' ";
			$res = $dbr->query( $sql );
			$row = $dbr->fetchObject( $res );
		   
		   	$ratingpix = round($row->ratzinger,1)*25;
		  
		   	if ($row->ratzinger < 1) {
		   		$out = '<div class="file-rating">This file it\'s not yet rated';
		   	}else {
		   		$out = '<div class="file-rating">User\'s average rate: <b>'.round($row->ratzinger,1).'</b>';
		   	}
       
		   	$out .= '<ul class="star-rating" title="login or sign up to rate this file">';
		   	$out .= '<li class="current-rating" id="current-rating" style="width:'.$ratingpix.'px"></li>';
		   	$out .= ' <li title="1 star of 5" class="one-star"></li>
                 		<li title="2 stars of 5" class="two-stars"></li>
                 		<li title="3 stars of 5" class="three-stars"></li>
                 		<li title="4 stars of 5" class="four-stars"></li>
                 		<li title="5 stars of 5" class="five-stars"></li></ul>
				</div>';
		  }
		  return $out;
		  
		  $dbr->freeResult( $res );
		}


	public function render_file() 
	{ 	
		global $wgTitle, $wgOut, $wgRequest, $wgScript, $wgUser;
		$wgOut->switchBocataMode(true);
		$wgOut->setOrder(-1);
                $wgOut->addScript("<script type=\"text/javascript\" src=\"/skins/soundshare/rating.js\"></script>\n");

		//check if the value is numeric
		if (is_numeric($this->id)) {
				$dbr = wfGetDB( DB_SLAVE );
	    		$sql = "SELECT f.IdFile, f.Filename, f.Size, f.Count, f.Bitrate, f.Length, f.Title, f.Artist, f.Album, f.Genre, f.Year, f.SHA1, f.ed2k FROM ss_file f INNER JOIN ss_tags_file tf ON tf.idfile=f.idfile inner join ss_tags t on t.idtags=tf.idtags WHERE t.artistkey='{$wgTitle->mArtistKey}' and t.titlekey='{$wgTitle->mNoArtistKey}' and tf.IdFile = ".mysql_real_escape_string($this->id);
	    		$res = $dbr->query( $sql );
		} else{
			header("Location:/"); //goto hell
		}
		
		//fetch the sql query
		$row = $dbr->fetchObject( $res );

		// Validate idfile matches with song info
		if ($row==null ) { // validate if is number the id from url
			$wgOut->redirect($wgTitle->getLocalURL(''), 301);
	        } else {
		
			
		if (!is_null( $row->Size ) || $row->Size <= 1 ) {
			$file_size = ByteSize( $row->Size );
		}
		if (!is_null( $row->Length )) {
			
			$row->Length = convertS2String($row->Length);
			$file_lenght =  '('.trim($row->Length).')';
		}
		if (!is_null( $row->Bitrate)) {
			$row->Bitrate = str_replace('~', '', $row->Bitrate);
			$file_bitrate  = $row->Bitrate.' kbit/s';
		}
		if (!is_null( $row->Count )) {
			$file_count  = '<span>Sources: '.$row->Count.' </span>';
		}
		
		if (!is_null( $row->Artist )) {
		  //echo $row->Artist;
		  $file_artist = urlencode( $row->Artist);
		  //$file_artist = '<span>Artist: <a href="'.$wgScript.'/Artist:'.ucwords($row->Artist).'">'.ucwords($row->Artist).'</a></span>';
		}
		if (!is_null( $row->Title )) {
			$file_title = '<span>Title: <a href="'.$wgScript.'/Song:'.ucwords($row->Title).'">'.ucwords($row->Title).'</a></span>';
		}
		if (!is_null( $row->Filename )) {
			$file_name = 'File: '.ucwords($row->Filename);
		}
		if (!is_null( $row->Album )) {
		  $file_album =  '<span>Release: <a href="'.$wgScript.'/Release:'.$row->Album.'">'.$row->Album.'</a></span>';
		}
		if (!is_null( $row->Genre )) {
		  $file_genre =  '<span>Genre: <a href="'.$wgScript.'/Category:'.ucwords($row->Genre).'">'.ucwords($row->Genre).'</a></span>';
		}
		
		//if not empty ed2k we paint the link
		if (!is_null($row->ed2k)) {

		  $urlstring = $row->Filename.'|'.$row->Size.'|'.$row->ed2k;
		  $file_ed2k =  '<div title="download '.$row->Filename.
		  ' on ed2k format"><img alt="ed2k download" src="'.'/skins/soundshare/emule_logo20x20.gif" />
		  <a  href="ed2k://|file|'.$row->Filename.'|'.$row->Size.'|'.$row->ed2k.'|/"
		  onclick="trackfile('.$row->IdFile.' ,\'ed2k\');" >ed2k://|file|'.truncateString($urlstring, 80).' </a></div>';
		
		}
	
		if (!is_null($row->SHA1) || !is_null($row->Tiger) || !is_null($row->MD5) || !is_null($row->ed2k)) {
		 $file_magnet_link = '<div title="download magnet link '.$row->Filename.' on magnetic link format">
		 <img alt="magnetic link download" src="'.'/skins/soundshare/magnet-icon-12x12.gif" />
		 <a href="magnet:?xt=urn:ed2k:'.$row->ed2k.'&xt=urn:sha1:'.$row->SHA1.'&dn='.$row->Filename.'"
		 onclick="trackfile('.$row->IdFile.' ,\'magnet\');" >
		 magnet:?xt=urn:'.truncateString($row->Filename, 70).'</a></div>';
		
		}
		
		$idfile = $row->IdFile;
			
		$sharelinks = '
		<a href="http://www.facebook.com/share.php?u=http://soundshare.com/download/'.$row->Artist.'/'.$row->Filename.'">
		<img alt="" src="/skins/soundshare/ico_facebook.gif" border = "0"/></a>
		
		<a href="http://www.myspace.com/Modules/PostTo/Pages/?u=http://soundshare.com/download/'.$row->Artist.'/'.$row->Filename.'">
		<img alt="" src="/skins/soundshare/ico_myspace.png" border = "0"/></a>
		
		<a href="mailto:mailto:?subject='.$row->Filename.'&body=http://soundshare.com/download/'.$row->Artist.'/'.$row->Filename.'">
		<img alt="" src="/skins/soundshare/email_link.png" border = "0"/></a>
		
		<a href="http://twitter.com/home?status=http://soundshare.com/download/'.$row->Artist.'/'.$row->Filename.'">
		<img alt="" src="/skins/soundshare/ico_twitter.png" border = "0"/></a>
		
		<br />
		';

              
		$wgOut->addHTML($this->getRatingFile($idfile)."
				<div class='share-links'>$sharelinks</div>
				<h1>{$row->Title}</h1>
				
				
				<div class='ddata'>{$file_name},  ({$file_size})</div>");
                 $wgOut->addHTML('<div class=\'ddata-album\'>Album :<a href="/music/'.urlencode($file_artist).'/album/'.urlencode($row->Album).' ">'.$row->Album.'</a></div>');

		$wgOut->addHTML("<table class='tabledatafile' >
				<TR>
				   <TH>Artist</TH>
				   <TH>Song Title</TH>
				   <TH>Size</TH>
				   <TH>Lenght</TH>
				   <TH>Bitrate</TH>
				   <TH>Sources</TH>
				</TR>
				<TR>
				   <TD><a href='/music/{$file_artist}'>{$row->Artist}</a></TD>
				   <TD>{$row->Title}</TD>
				   <TD>{$file_size}</TD>
				   <TD>{$row->Length}</TD>
				   <TD>{$file_bitrate}</TD>
				   <TD>{$row->Count}</TD>
				</TR>
				
				</TABLE> 
		
				<div id='dlinks' class='dlinks'>$file_ed2k$file_magnet_link</div>
		");		
		$wgOut->resetOrder();
		$wgOut->switchBocataMode(false);
		
		$wgOut->setOrder(1000000);
		
		
		$wgOut->addHTML($this->getCommentsFile($row->IdFile , $row->Artist, $row->Title));
		
		
		if( $wgUser->isLoggedIn() ) {
			
			$wgOut->addHTML('
					<div class="dcomment">
						<div class="dcomment_soundsy">
						<img alt="" src="/skins/soundshare/soundsy-bocata-comment.gif" border = "0"/>
						</div>
					
					<div class="bubble">
						<div class="rounded">
						
						<form name="savecomment"  method="post" action="/ss_saveFileComment.php">
						<input name="id_file" value="'.$row->IdFile.'" type="hidden">
						<textarea name="comment" id="comment" maxlenght="350"
						onfocus="this.value=\'\';">'.wfMsg('write_here_your_comment').'</textarea><br>
						<input class="searchButton"  value="Send comment" type="submit">
						</form>	  
						</div>
					</div>');
		}
		
		
		$wgOut->resetOrder();
		
		$dbr->freeResult( $res );     
		
		} 
		
	}	
	
	
	
} //end of class MP3
